package com.hframe.http.client;

import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by heqian on 12/6/16.
 */

public abstract class StringSuccess implements Success {
    protected ArrayList<Progress.DataItem> datas = null;

    public abstract void onString(String string);

    @Override
    public void setHttpClient(HttpClients client) {

    }

    @Override
    public void start(HttpURLConnection connection) throws Exception {
        datas = new ArrayList<>();
    }

    @Override
    public void finish(HttpURLConnection connection) throws Exception {
        byte[] bytes = DataListToBytes(datas);
        if (null != bytes)
            onString(new String(bytes));
    }

    @Override
    public boolean onDownload(Progress.DataItem data, HttpURLConnection connection) throws Exception {
        datas.add(data);
        return true;
    }

    public byte[] DataListToBytes(List<Progress.DataItem> list) {
        int length = 0;
        for (Progress.DataItem item : list)
            length += item.length;

        if (0 < length) {
            byte[] ret = new byte[length];

            length = 0;
            for (Progress.DataItem item : list) {
                System.arraycopy(item.data, 0, ret, length, item.length);
                length += item.length;
            }
            return ret;
        }
        return null;
    }
}
